// 卡牌游戏主逻辑
class CardGame {
    constructor() {
        this.playerHealth = 30;
        this.enemyHealth = 30;
        this.playerHand = [];
        this.playerBattlefield = [];
        this.enemyBattlefield = [];
        this.currentTurn = 'player';
        this.gameOver = false;
        this.maxHandSize = 7;
        this.maxBattlefieldSize = 5;
        
        this.initParticles();
        this.initGame();
        this.bindEvents();
    }
    
    // 卡牌定义
    getCardTemplates() {
        return [
            { name: '战士', attack: 4, health: 3, image: 'resources/card-warrior.png', rarity: 'common' },
            { name: '法师', attack: 3, health: 2, image: 'resources/card-mage.png', rarity: 'rare' },
            { name: '巨龙', attack: 6, health: 5, image: 'resources/card-dragon.png', rarity: 'legendary' },
            { name: '治疗师', attack: 2, health: 4, image: 'resources/card-healer.png', rarity: 'common' },
            { name: '盗贼', attack: 3, health: 2, image: 'resources/card-rogue.png', rarity: 'rare' }
        ];
    }
    
    // 初始化粒子效果
    initParticles() {
        const canvas = document.getElementById('particles-canvas');
        const ctx = canvas.getContext('2d');
        
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        
        const particles = [];
        const particleCount = 50;
        
        // 创建粒子
        for (let i = 0; i < particleCount; i++) {
            particles.push({
                x: Math.random() * canvas.width,
                y: Math.random() * canvas.height,
                vx: (Math.random() - 0.5) * 0.5,
                vy: (Math.random() - 0.5) * 0.5,
                size: Math.random() * 3 + 1,
                opacity: Math.random() * 0.5 + 0.2,
                color: `hsl(${Math.random() * 60 + 200}, 70%, 60%)`
            });
        }
        
        // 动画循环
        const animate = () => {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            particles.forEach(particle => {
                particle.x += particle.vx;
                particle.y += particle.vy;
                
                // 边界检查
                if (particle.x < 0 || particle.x > canvas.width) particle.vx *= -1;
                if (particle.y < 0 || particle.y > canvas.height) particle.vy *= -1;
                
                // 绘制粒子
                ctx.save();
                ctx.globalAlpha = particle.opacity;
                ctx.fillStyle = particle.color;
                ctx.beginPath();
                ctx.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2);
                ctx.fill();
                ctx.restore();
            });
            
            requestAnimationFrame(animate);
        };
        
        animate();
        
        // 响应窗口大小变化
        window.addEventListener('resize', () => {
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;
        });
    }
    
    // 初始化游戏
    initGame() {
        this.playerHealth = 30;
        this.enemyHealth = 30;
        this.playerHand = [];
        this.playerBattlefield = [];
        this.enemyBattlefield = [];
        this.currentTurn = 'player';
        this.gameOver = false;
        
        // 初始发牌
        for (let i = 0; i < 5; i++) {
            this.drawCard('player');
        }
        
        this.updateUI();
        this.renderHand();
        this.renderBattlefield();
    }
    
    // 抽牌
    drawCard(target) {
        if (target === 'player' && this.playerHand.length >= this.maxHandSize) {
            return;
        }
        
        const templates = this.getCardTemplates();
        const randomCard = templates[Math.floor(Math.random() * templates.length)];
        const card = {
            id: Date.now() + Math.random(),
            ...randomCard,
            currentHealth: randomCard.health
        };
        
        if (target === 'player') {
            this.playerHand.push(card);
        }
        
        this.updateUI();
        this.renderHand();
    }
    
    // 创建卡牌元素
    createCardElement(card, isInHand = true) {
        const cardElement = document.createElement('div');
        cardElement.className = 'card';
        cardElement.dataset.cardId = card.id;
        
        cardElement.innerHTML = `
            <div class="card-face card-back"></div>
            <div class="card-face card-front">
                <div class="card-image" style="background-image: url('${card.image}')"></div>
                <div class="card-stats">
                    <span>攻:${card.attack}</span>
                    <span>血:${card.currentHealth}</span>
                </div>
                <div class="card-name">${card.name}</div>
            </div>
        `;
        
        if (isInHand) {
            this.addHandCardEvents(cardElement, card);
        }
        
        return cardElement;
    }
    
    // 添加手牌事件
    addHandCardEvents(cardElement, card) {
        let isDragging = false;
        let startX, startY;
        let originalTransform = '';
        
        // 触摸/鼠标事件
        const handleStart = (e) => {
            if (this.currentTurn !== 'player' || this.gameOver) return;
            
            isDragging = true;
            const clientX = e.clientX || e.touches[0].clientX;
            const clientY = e.clientY || e.touches[0].clientY;
            startX = clientX;
            startY = clientY;
            
            originalTransform = cardElement.style.transform;
            cardElement.classList.add('dragging');
            
            // 翻转卡牌显示正面
            cardElement.classList.add('flipped');
        };
        
        const handleMove = (e) => {
            if (!isDragging || !this.currentTurn === 'player' || this.gameOver) return;
            
            e.preventDefault();
            const clientX = e.clientX || e.touches[0].clientX;
            const clientY = e.clientY || e.touches[0].clientY;
            
            const deltaX = clientX - startX;
            const deltaY = clientY - startY;
            
            cardElement.style.transform = `translate(${deltaX}px, ${deltaY}px) scale(1.2)`;
            
            // 检查是否在投放区域
            const playerDropZone = document.getElementById('playerDropZone');
            const rect = playerDropZone.getBoundingClientRect();
            
            if (clientX >= rect.left && clientX <= rect.right && 
                clientY >= rect.top && clientY <= rect.bottom) {
                playerDropZone.classList.add('drag-over');
            } else {
                playerDropZone.classList.remove('drag-over');
            }
        };
        
        const handleEnd = (e) => {
            if (!isDragging || this.currentTurn !== 'player' || this.gameOver) return;
            
            isDragging = false;
            cardElement.classList.remove('dragging');
            cardElement.style.transform = originalTransform;
            
            const clientX = e.clientX || e.changedTouches[0].clientX;
            const clientY = e.clientY || e.changedTouches[0].clientY;
            
            // 检查是否在投放区域
            const playerDropZone = document.getElementById('playerDropZone');
            const rect = playerDropZone.getBoundingClientRect();
            
            if (clientX >= rect.left && clientX <= rect.right && 
                clientY >= rect.top && clientY <= rect.bottom) {
                this.playCard(card);
            }
            
            playerDropZone.classList.remove('drag-over');
        };
        
        // 事件监听
        cardElement.addEventListener('mousedown', handleStart);
        cardElement.addEventListener('touchstart', handleStart);
        
        document.addEventListener('mousemove', handleMove);
        document.addEventListener('touchmove', handleMove);
        
        document.addEventListener('mouseup', handleEnd);
        document.addEventListener('touchend', handleEnd);
        
        // 点击翻转
        cardElement.addEventListener('click', () => {
            if (this.currentTurn !== 'player' || this.gameOver) return;
            cardElement.classList.toggle('flipped');
        });
    }
    
    // 打出卡牌
    playCard(card) {
        if (this.playerBattlefield.length >= this.maxBattlefieldSize) {
            this.showMessage('战场已满！');
            return;
        }
        
        // 从手牌移除
        this.playerHand = this.playerHand.filter(c => c.id !== card.id);
        
        // 添加到战场
        this.playerBattlefield.push(card);
        
        // 添加出场动画
        this.animateCardPlay(card);
        
        this.updateUI();
        this.renderHand();
        this.renderBattlefield();
    }
    
    // 卡牌出场动画
    animateCardPlay(card) {
        const cardElement = this.createCardElement(card, false);
        cardElement.style.position = 'fixed';
        cardElement.style.zIndex = '1000';
        cardElement.style.left = '50%';
        cardElement.style.top = '70%';
        cardElement.style.transform = 'translate(-50%, -50%) scale(1.5)';
        cardElement.classList.add('flipped');
        
        document.body.appendChild(cardElement);
        
        anime({
            targets: cardElement,
            left: '50%',
            top: '50%',
            scale: 1,
            duration: 800,
            easing: 'easeOutCubic',
            complete: () => {
                document.body.removeChild(cardElement);
            }
        });
    }
    
    // 渲染手牌
    renderHand() {
        const handArea = document.getElementById('handArea');
        handArea.innerHTML = '';
        
        this.playerHand.forEach(card => {
            const cardElement = this.createCardElement(card);
            handArea.appendChild(cardElement);
        });
    }
    
    // 渲染战场
    renderBattlefield() {
        const playerDropZone = document.getElementById('playerDropZone');
        const enemyDropZone = document.getElementById('enemyDropZone');
        
        playerDropZone.innerHTML = '';
        enemyDropZone.innerHTML = '';
        
        // 玩家战场
        if (this.playerBattlefield.length === 0) {
            playerDropZone.innerHTML = '<span style="color: #ffd700; font-family: \"Orbitron\", monospace;">你的战场</span>';
        } else {
            this.playerBattlefield.forEach(card => {
                const cardElement = this.createCardElement(card, false);
                cardElement.classList.add('flipped');
                playerDropZone.appendChild(cardElement);
            });
        }
        
        // 敌人战场
        if (this.enemyBattlefield.length === 0) {
            enemyDropZone.innerHTML = '<span style="color: #ffd700; font-family: \"Orbitron\", monospace;">敌人战场</span>';
        } else {
            this.enemyBattlefield.forEach(card => {
                const cardElement = this.createCardElement(card, false);
                cardElement.classList.add('flipped');
                enemyDropZone.appendChild(cardElement);
            });
        }
    }
    
    // 结束回合
    endTurn() {
        if (this.currentTurn !== 'player' || this.gameOver) return;
        
        this.currentTurn = 'enemy';
        this.updateUI();
        
        // 玩家攻击
        this.performAttack('player');
        
        if (this.checkGameOver()) return;
        
        // 敌人回合
        setTimeout(() => {
            this.enemyTurn();
        }, 1500);
    }
    
    // 敌人回合
    enemyTurn() {
        // 敌人抽牌
        if (Math.random() < 0.7) {
            const templates = this.getCardTemplates();
            const randomCard = templates[Math.floor(Math.random() * templates.length)];
            const card = {
                id: Date.now() + Math.random(),
                ...randomCard,
                currentHealth: randomCard.health
            };
            
            if (this.enemyBattlefield.length < this.maxBattlefieldSize) {
                this.enemyBattlefield.push(card);
            }
        }
        
        // 敌人攻击
        this.performAttack('enemy');
        
        if (this.checkGameOver()) return;
        
        // 回到玩家回合
        setTimeout(() => {
            this.currentTurn = 'player';
            this.drawCard('player');
            this.updateUI();
            this.renderHand();
            this.renderBattlefield();
        }, 1500);
    }
    
    // 执行攻击
    performAttack(attacker) {
        if (attacker === 'player') {
            // 玩家攻击敌人
            const totalDamage = this.playerBattlefield.reduce((sum, card) => sum + card.attack, 0);
            if (totalDamage > 0) {
                this.enemyHealth -= totalDamage;
                this.animateDamage('enemy', totalDamage);
            }
        } else {
            // 敌人攻击玩家
            const totalDamage = this.enemyBattlefield.reduce((sum, card) => sum + card.attack, 0);
            if (totalDamage > 0) {
                this.playerHealth -= totalDamage;
                this.animateDamage('player', totalDamage);
            }
        }
    }
    
    // 伤害动画
    animateDamage(target, damage) {
        const healthBar = document.getElementById(target === 'player' ? 'playerHealth' : 'enemyHealth');
        
        // 创建伤害数字
        const damageText = document.createElement('div');
        damageText.textContent = `-${damage}`;
        damageText.style.cssText = `
            position: absolute;
            color: #ff0000;
            font-size: 24px;
            font-weight: bold;
            z-index: 1000;
            pointer-events: none;
            font-family: 'Orbitron', monospace;
        `;
        
        const rect = healthBar.getBoundingClientRect();
        damageText.style.left = rect.left + rect.width / 2 + 'px';
        damageText.style.top = rect.top + 'px';
        
        document.body.appendChild(damageText);
        
        // 动画
        anime({
            targets: damageText,
            translateY: -50,
            opacity: [1, 0],
            duration: 1000,
            easing: 'easeOutCubic',
            complete: () => {
                document.body.removeChild(damageText);
            }
        });
        
        // 血条震动
        healthBar.classList.add('damage-animation');
        setTimeout(() => {
            healthBar.classList.remove('damage-animation');
        }, 500);
    }
    
    // 检查游戏结束
    checkGameOver() {
        if (this.playerHealth <= 0) {
            this.gameOver = true;
            this.showGameOver('你输了！');
            return true;
        } else if (this.enemyHealth <= 0) {
            this.gameOver = true;
            this.showGameOver('你赢了！');
            return true;
        }
        return false;
    }
    
    // 显示游戏结束
    showGameOver(message) {
        const modal = document.getElementById('gameOverModal');
        const title = document.getElementById('gameOverTitle');
        
        title.textContent = message;
        modal.style.display = 'flex';
        
        anime({
            targets: modal,
            opacity: [0, 1],
            duration: 500,
            easing: 'easeOutCubic'
        });
        
        anime({
            targets: '.game-over-content',
            scale: [0.8, 1],
            opacity: [0, 1],
            duration: 600,
            delay: 200,
            easing: 'easeOutBack'
        });
    }
    
    // 显示消息
    showMessage(message) {
        const messageDiv = document.createElement('div');
        messageDiv.textContent = message;
        messageDiv.style.cssText = `
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0, 0, 0, 0.8);
            color: #ffd700;
            padding: 15px 30px;
            border-radius: 10px;
            font-family: 'Orbitron', monospace;
            font-weight: 600;
            z-index: 1000;
            border: 2px solid #ffd700;
        `;
        
        document.body.appendChild(messageDiv);
        
        setTimeout(() => {
            document.body.removeChild(messageDiv);
        }, 2000);
    }
    
    // 更新UI
    updateUI() {
        const turnIndicator = document.getElementById('turnIndicator');
        const playerHealthBar = document.getElementById('playerHealth');
        const enemyHealthBar = document.getElementById('enemyHealth');
        const endTurnBtn = document.getElementById('endTurnBtn');
        
        turnIndicator.textContent = this.currentTurn === 'player' ? '玩家回合' : '敌人回合';
        playerHealthBar.textContent = `玩家血量: ${this.playerHealth}`;
        enemyHealthBar.textContent = `敌人血量: ${this.enemyHealth}`;
        
        endTurnBtn.disabled = this.currentTurn !== 'player' || this.gameOver;
        
        // 添加发光效果
        if (this.currentTurn === 'player') {
            turnIndicator.classList.add('glowing');
        } else {
            turnIndicator.classList.remove('glowing');
        }
    }
    
    // 绑定事件
    bindEvents() {
        const endTurnBtn = document.getElementById('endTurnBtn');
        const restartBtn = document.getElementById('restartBtn');
        
        endTurnBtn.addEventListener('click', () => this.endTurn());
        restartBtn.addEventListener('click', () => this.restart());
    }
    
    // 重新开始
    restart() {
        const modal = document.getElementById('gameOverModal');
        modal.style.display = 'none';
        
        this.initGame();
    }
}

// 初始化游戏
let game;
document.addEventListener('DOMContentLoaded', () => {
    game = new CardGame();
});

// 防止页面滚动
document.addEventListener('touchmove', (e) => {
    e.preventDefault();
}, { passive: false });

// 防止双击缩放
document.addEventListener('dblclick', (e) => {
    e.preventDefault();
});